 /* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Mario Costa |  */

function currencyFormat(fld, milSep, decSep, e) {
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = /^\d|[a-z]|[A-Z]|[\`]$/;  
  var strCheckFirst = /^\d$/;  
    
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;
  if (whichCode == 13) return true;  // Enter
  if (e.keyCode == 8) return true;  // Delete
  if (e.keyCode == 9) return true;  // Tab
  if (e.keyCode == 37) return true;  // up
  if (e.keyCode == 38) return true;  // down
  if (e.keyCode == 39) return true;  // left
  if (e.keyCode == 40) return true;  // right
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if(!strCheck.test(key)){
  	return false;
  }  
  
  len = fld.value.length;
  for(i = 0; i < len; i++)
    if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;

  for(; i < len; i++){
  	if(strCheckFirst.test(fld.value.charAt(i))){
    	aux += fld.value.charAt(i);  	
  	}    
  }
  //aux += key;
  len = aux.length;
  // Block only support Gecko
  var o = document.createElement("input");
  var isStandard = "selectionStart" in o;
  var posCursor = 0;
  if(isStandard){
  	if((len % 3) == 1)
  		posCursor = fld.selectionStart + 1;
  	else
  		posCursor = fld.selectionStart;
  	// Check decimal
  	if((fld.value.indexOf(".") > -1) || ((decSep != "") && (len == 3)) ){
  		posCursor += 1;  		  		
  	}
  }	
  // End Block

  if (len == 0) fld.value = '';
  //if (len == 1) fld.value = '0'+ decSep + '0' + aux;
  //if (len == 2) fld.value = '0'+ decSep + aux;  

  if (len > 2) {
    aux2 = '';
    // If decStep = "" exist. not decimal
    i = decSep != "" ? len - 3 : len - 1;
    for (j = 0; i >= 0; i--) {
      if (j == 3) {
        aux2 += milSep;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;

    for (i = len2 - 1; i >= 0; i--)
      fld.value += aux2.charAt(i);
	
    fld.value += (decSep != "") ? decSep + aux.substr(len - 2, len) : "";
  }
	// Block only support Gecko
	if(isStandard){
		fld.setSelectionRange(posCursor, posCursor);
	}
	// End Block  
  return false;
}